package com.manage.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.manage.entity.User;

import java.util.Date;

public class JwtUtils {

    private static String secretKey="secretKey";

    private long expiration=3600000;

    public String getSecretKey(User user) {
        return JWT.create()
                .withSubject(user.getId().toString())
                .withClaim("username",user.getUsername())
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis()+expiration))
                .sign(Algorithm.HMAC256(secretKey));
    }

    // 解析并验证Token的方法
    public DecodedJWT verifyToken(String token) throws JWTVerificationException {
        Algorithm algorithm = Algorithm.HMAC256(secretKey);
        JWTVerifier verifier = JWT.require(algorithm)
                .build();
        return verifier.verify(token);
    }

    // 从Token中获取用户ID
    public Long getUserIdFromToken(String token) {
        DecodedJWT jwt = verifyToken(token);
        return Long.parseLong(jwt.getSubject());
    }

    // 从Token中获取用户名
    public String getUsernameFromToken(String token) {
        DecodedJWT jwt = verifyToken(token);
        return jwt.getClaim("username").asString();
    }

    // 检查Token是否过期
    public boolean isTokenExpired(String token) {
        DecodedJWT jwt = verifyToken(token);
        return jwt.getExpiresAt().before(new Date());
    }
}
